package com.itheima.entity.filter;


import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //0.强转对象
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;


        //1.获取请求 URL
//        StringBuffer url = req.getRequestURL();
        String uri = req.getRequestURI();
        //2.判断请求 URl 中是否包含 login，如果包含，说明是登录操作，直接放行
        if(uri.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //3.获取请求头中的令牌（token)
        String token = req.getHeader("token");
        //4.解析 token，如果解析失败，响应 401
        if(token == null){
            //前端写好的逻辑，报 401就会自动跳到登录页面
            resp.setStatus(401);
            return;
        }

        //5.解析 token，如果解析失败，响应 401

        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("claims={}",claims);
        } catch (Exception e) {
            //前端写好的逻辑，报 401就会自动跳到登录页面
            resp.setStatus(401);
            return;
        }


        //6.放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
